package ltd.dujiabao.performance.monitor.pm.listener;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;
import ltd.dujiabao.performance.monitor.pm.domain.PerformanceAdapter;
import ltd.dujiabao.performance.monitor.pm.event.CollectEvent;
import ltd.dujiabao.performance.monitor.pm.storage.PerformanceStorage;

/**
 * @author : DuJiabao
 * @Project : performance_monitor
 * @Time : 2022/2/27 20:49
 * @Desc : 监听收集事件
 */
@Slf4j
@Component
public class CollectListener implements ApplicationListener<CollectEvent> {
    private final PerformanceStorage performanceStorage;

    @Autowired
    public CollectListener(PerformanceStorage performanceStorage) {
        this.performanceStorage = performanceStorage;
    }

    @Override
    public void onApplicationEvent(CollectEvent collectEvent) {
        Long timeConsuming = collectEvent.getTimeConsuming();
        String[] urls = collectEvent.getUrls();
        log.info("listen time consuming : {}, urls : {}", timeConsuming, Arrays.toString(urls));
        this.doEvent(collectEvent);
    }

    /**
     * 真正处理时间的方法
     *
     * @param collectEvent 收集事件
     */
    public  void doEvent(CollectEvent collectEvent){
        performanceStorage.store(PerformanceAdapter.toPerformances(collectEvent));
    }
}
